package com.fengfeng.http;

import android.util.Log;

import com.fengfeng.utils.FFLogUtils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;

/**
 * Post进行网络请求的工具类
 * 这一步骤相当于 sdk文档中 进行初始化的步骤
 */

public class HttpUtils {

    public static void doPost(String urlStr, HashMap<String, Object> data, HttpCallback callback) { //了解POST请求的写法
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                DataOutputStream wr = null;
                String line;
                StringBuilder response = new StringBuilder();
                try {
                    URL url = new URL(urlStr);
                    conn = (HttpURLConnection) url.openConnection();

                    // 设置请求方法为POST
                    conn.setRequestMethod("POST");

                    // 设置请求体类型为application/x-www-form-urlencoded
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                    // 设置请求允许输出
                    conn.setDoOutput(true);

                    // 设置请求允许输入
                    conn.setDoInput(true);

                    // 不使用缓存
                    conn.setUseCaches(false);

                    // 允许从该连接中读取输入流
                    conn.connect();
                    String postString = paramMapToString(data);
                    FFLogUtils.i("请求的参数:" + postString);
                    // 将请求参数发送到服务器
                    wr = new DataOutputStream(conn.getOutputStream());
                    wr.writeBytes(postString);
                    wr.flush();
                    wr.close();

                    // 获取响应状态码
                    int responseCode = conn.getResponseCode();
                    FFLogUtils.i("Response Code : " + responseCode);
                    BufferedReader br = new BufferedReader(
                        new InputStreamReader((conn.getInputStream())));
                    if (responseCode == 200) {
                        while ((line = br.readLine()) != null) {
                            response.append(line);
                        }
                        if (response.toString().isEmpty()) {
                            //防止内容为空
                            callback.error(responseCode, "请求接口异常:返回内容为空");
                            return;
                        }
                        JSONObject jsonObject = new JSONObject(response.toString());
                        int code = jsonObject.optInt("code", -1);
                        JSONObject responData = jsonObject.getJSONObject("data"); // 获取名为"data"的JSONObject
                        String msg = jsonObject.optString("msg", "");
                        if (code == 0) {
                            callback.success(responData, msg);
                        } else {
                            callback.error(code, msg);
                        }

                    } else {
                        callback.error(responseCode, "请求接口异常:" + responseCode);
                    }

                    // 关闭流
                    br.close();
                } catch (Exception e) {
                    callback.error(-1, "请求接口异常:" + e.toString());
                    e.printStackTrace();
                } finally {
                    // 关闭连接
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();

    }

    private static String paramMapToString(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return "";
        }

        StringBuilder queryString = new StringBuilder();
        boolean firstParam = true; // 用于标记是否为第一个参数

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!firstParam) {
                queryString.append("&"); // 如果不是第一个参数，则添加&
            }
            queryString.append(entry.getKey()).append("=").append(entry.getValue().toString());
            firstParam = false; // 标记后续参数不是第一个
        }
        return queryString.toString();
    }


}